import { Footer } from '@/components';
import { PROJECT_NAME } from '@/constants';
import { userRegisterUsingPost } from '@/services/backend/userController';
import { Link } from '@@/exports';
import { Helmet, history } from '@umijs/max';
import { Button, Form, Input, message, Popover } from 'antd';
import React, { useState } from 'react';
import Settings from '../../../../config/defaultSettings';
import useStyles from './index.style';

const FormItem = Form.Item;

const Register: React.FC = () => {
  const { styles } = useStyles();

  const [popover, setPopover]: [boolean, any] = useState(false);
  const [open, setVisible]: [boolean, any] = useState(false);
  const [form] = Form.useForm();
  const confirmDirty = false;
  const passwordStatusMap = {
    ok: (
      <div className={styles.success}>
        <span>强度：强</span>
      </div>
    ),
    pass: (
      <div className={styles.warning}>
        <span>强度：中</span>
      </div>
    ),
    poor: (
      <div className={styles.error}>
        <span>强度：太短</span>
      </div>
    ),
  };

  const getPasswordStatus = () => {
    const value = form.getFieldValue('password');
    if (value && value.length > 9) {
      return 'ok';
    }
    if (value && value.length > 5) {
      return 'pass';
    }
    return 'poor';
  };

  const onFinish = async (values: API.UserRegisterRequest) => {
    try {
      // 注册
      const res = await userRegisterUsingPost({
        ...values,
      });
      if (res.code === 0) {
        const defaultLoginSuccessMessage = '注册成功,正在跳转至登录~';
        message.success(defaultLoginSuccessMessage);

        const urlParams = new URL(window.location.href).searchParams;
        history.push(urlParams.get('redirect') || '/user/login');
        return;
      }
    } catch (error: any) {
      const defaultLoginFailureMessage = `注册失败，${error.message}`;
      message.error(defaultLoginFailureMessage);
    }
  };

  const checkPassword = (_: any, value: string) => {
    const promise = Promise;
    // 没有值的情况
    if (!value) {
      setVisible(!!value);
      return promise.reject('请输入密码!');
    }
    // 有值的情况
    if (!open) {
      setVisible(!!value);
    }
    setPopover(!popover);
    if (value.length < 6) {
      return promise.reject('');
    }
    if (value && confirmDirty) {
      form.validateFields(['confirm']);
    }
    return promise.resolve();
  };

  const checkConfirm = (_: any, value: string) => {
    const promise = Promise;
    if (value && value !== form.getFieldValue('password')) {
      return promise.reject('两次输入的密码不匹配!');
    }
    return promise.resolve();
  };

  return (
    <div className={styles.container}>
      <Helmet>
        <title>
          {'注册'}- {Settings.title}
        </title>
      </Helmet>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
          display: 'flex',
          margin: '0 auto',
          width: '328px',
          flexDirection: 'column',
          justifyContent: 'center',
        }}
      >
        <span
          style={{
            position: 'relative',
            insetBlockStart: '2px',
            fontWeight: '600',
            fontSize: '33px',
            textAlign: 'center',
            paddingBottom: '15px',
          }}
        >
          注册
        </span>
        <Form
          title={PROJECT_NAME}
          form={form}
          name="UserRegister"
          style={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          onFinish={onFinish}
        >
          <FormItem
            name="account"
            rules={[
              {
                required: true,
                message: '请输入账号!',
              },
            ]}
          >
            <Input size="large" placeholder="账号" />
          </FormItem>
          <Popover
            getPopupContainer={(node) => {
              if (node && node.parentNode) {
                return node.parentNode as HTMLElement;
              }
              return node;
            }}
            content={
              open && (
                <div
                  style={{
                    padding: '4px 0',
                  }}
                >
                  {passwordStatusMap[getPasswordStatus()]}
                  <div
                    style={{
                      marginTop: 10,
                    }}
                  >
                    <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
                  </div>
                </div>
              )
            }
            overlayStyle={{
              width: 240,
            }}
            placement="right"
            open={open}
          >
            <FormItem
              name="password"
              className={
                form.getFieldValue('password') &&
                form.getFieldValue('password').length > 0 &&
                styles.password
              }
              rules={[
                {
                  validator: checkPassword,
                },
              ]}
            >
              <Input size="large" type="password" placeholder="至少6位密码，区分大小写" />
            </FormItem>
          </Popover>
          <FormItem
            name="checkPassword"
            rules={[
              {
                required: true,
                message: '确认密码',
              },
              {
                validator: checkConfirm,
              },
            ]}
          >
            <Input size="large" type="password" placeholder="确认密码" />
          </FormItem>
          <FormItem>
            <div className={styles.footer}>
              <Button size="large" className={styles.submit} type="primary" htmlType="submit">
                <span>注册</span>
              </Button>
              <Link to="/user/login">
                <span>使用已有账户登录</span>
              </Link>
            </div>
          </FormItem>
        </Form>
      </div>
      <Footer />
    </div>
  );
};
export default Register;
